package yxy.banana.server.internal;

import java.io.IOException;

import com.google.protobuf.InvalidProtocolBufferException;

import yxy.apple.logger.Logger;
import yxy.banana.socket.controlled.ControlledHandler;
import yxy.banana.socket.controller.server.ServerRegistryController;

public abstract class InternalServerController<H extends ControlledHandler> extends ServerRegistryController<H> {

	private static final Logger logger = Logger.create(InternalServerController.class);

	public InternalServerController(int heartbeatTimeout, int registryTimeout) {
		super(heartbeatTimeout, registryTimeout);
	}

	@Override
	protected void unregistered() {
		this.handler().disconnect();
	}

	@Override
	protected void silenced() {
		logger.warn("出现心跳静默，连接将被强制断开！\r\n%s", this.toString());
		this.handler().disconnect();
	}

	@Override
	protected void announced() {
		logger.trace("收到心跳请求消息。\r\n%s", this.toString());
	}

	@Override
	protected void opened() {
		logger.trace("连接开启\r\n%s", this.toString());
	}

	@Override
	protected void closed() {
		logger.trace("连接关闭\r\n%s", this.toString());
	}

	@Override
	protected void actived() {
		logger.trace("连接可用bbb\r\n%s", this.toString());
	}

	@Override
	protected void inactived() {
		logger.trace("连接失活\r\n%s", this.toString());
	}

	@Override
	protected void triggered(Object event) {
		logger.warn("发生预期外的事件(%s)触发，请检查代码！\r\n%s", event, this.toString());
	}

	@Override
	protected void thrown(Throwable cause) {
		if (cause instanceof InvalidProtocolBufferException) {
			logger.error("捕获到InvalidProtocolBufferException异常，请检查代码！\r\n%s", this.toString());
			logger.error(cause);
		} else if (cause instanceof IOException) {
			// IO异常只计入trace
			logger.trace(cause);
		} else {
			logger.warn("捕获异常，请联系开发人员评估。\r\n%s", this.toString());
			logger.warn(cause);
		}
	}

	@Override
	protected void dropped(Object message, DroppedReason reason) {
		logger.warn("有消息存在问题被丢弃...\r\n原因：%s\r\n%s\r\n", reason.name(), message, this.toString());
	}
}
